import Locale from '@/components/SelectLang';
import { Affix, Button, Col, Divider, Flex, Popover, Space, message } from 'antd';
import React, { useEffect, useState } from 'react';

import code from '@/assets/app_code.png';
import donwImg from '@/assets/down_arrow.png';
import { handleUnreadFlag } from '@/services/login';
import { jumpUrl, productList } from '@/utils';
import { useGetToken } from '@/utils/request';
import { useRequest } from 'ahooks';
import { throttle } from 'lodash';
import { useIntl, useLocation, useModel } from 'umi';
import CountrySelect from '../CountrySelect';
import './index.less';

import userImg from '@/assets/user.svg';
import { donwLoad } from '@/utils';
type IProps = {
  dark?: boolean;
  isCommon?: boolean;
  style?: React.CSSProperties;
  fixed?: boolean;
  top?: number;
  needWords?: boolean;
  localOverlayClassName?: string;
};

const TopBar: React.FC<IProps> = ({
  dark,
  needWords = true,
  isCommon = true,
  style,
  fixed = false,
  top = 0,
  localOverlayClassName,
}) => {
  const intl = useIntl();
  const [isFixed, setFixed] = useState(false);
  const { token } = useGetToken();
  const location = useLocation();
  const { pathname: pnames } = location;
  const pname = pnames.replace('/en', '') || '/';

  const pathname = pname.split('/').length > 1 ? `/${pname.split('/')[1]}` : pname;
  const { user, run, setUser, cookie } = useModel('userModel');
  const {
    lastNameEn,
    firstNameEn,
    finishFillInfoDate,
    email,
    mobile,
    userNo,
    firstNameCn,
    lastNameCn,
  } = user || {};
  const cnName = `${firstNameCn}${lastNameCn}`;
  const enName = `${firstNameEn} ${lastNameEn}`;
  const isEn = intl.locale == 'en-US';

  const name = isEn ? enName : cnName;
  const newName = (firstNameCn && name) || email || mobile;
  const { data, run: run1 } = useRequest(handleUnreadFlag, { manual: true });
  const hasMsg = data?.data;

  useEffect(() => {
    if (token && !newName) {
      run();
    }
    if (token) {
      run1();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token, run, run1]);

  useEffect(() => {
    if (fixed && top) {
      window.addEventListener(
        'scroll',
        throttle(function () {
          // 获取滚动位置
          const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
          // 输出滚动位置
          if (scrollTop >= top) {
            setFixed(true);
          } else {
            setFixed(false);
          }
        }, 50),
      );
    }
  }, [fixed, top]);
  const jumpUrls = (params: string) => {
    jumpUrl(`/center?${params}`);
  };
  const items = [
    {
      key: 1,
      label: intl.formatMessage({ id: 'center.apply' }),
    },
    {
      key: 2,
      label: intl.formatMessage({ id: 'center.data' }),
    },

    {
      key: 3,
      label: intl.formatMessage({ id: 'center.msg' }),
    },
    {
      key: 4,
      label: intl.formatMessage({ id: 'center.setting' }),
    },
    {
      key: 5,
      label: intl.formatMessage({ id: 'home.out' }),
    },
  ];
  const color = dark ? '#333' : '#fff';
  const pathName = ['/', '/product', '/info'];
  const compoennt = (newStyle?: React.CSSProperties) => (
    <div
      style={{
        display: 'flex',
        justifyContent: 'space-between',
        paddingTop: 14,
        alignItems: 'center',
        position: 'relative',
        ...style,
        ...newStyle,
      }}
      className={!dark ? 'right_operate_word' : 'right_operate_dark_word'}
    >
      <div className="left">
        <Flex
          onClick={() => {
            if (token && finishFillInfoDate) {
              if (pathname == '/product') {
                return;
              }
              jumpUrl('/product');
            } else {
              if (pathname == '/') {
                return;
              }
              jumpUrl('/');
            }
          }}
          style={{
            cursor: 'pointer',
          }}
          gap={6}
          align="center"
        >
          <Col style={{ marginTop: -2 }}>
            <img
              src={require(`@/assets/${isEn ? 'en_' : ''}${dark ? 'b_logo' : 'logo'}.png`)}
              height={28}
            />
          </Col>
          <CountrySelect dark={dark} />
        </Flex>
      </div>

      <Space align="center" size={28} style={{ color, fontSize: 16 }}>
        {!pathName.includes(pathname) ? (
          <Popover
            overlayClassName="all_prodct"
            arrow={false}
            content={
              <div style={{ padding: '0px 10px' }}>
                {productList.map((item) => {
                  const { word, key } = item;
                  return (
                    <div
                      className="all_prodct_item"
                      style={{ fontSize: 15, marginBottom: 8 }}
                      key={key}
                      onClick={() => {
                        jumpUrl(`/more?productType=${key}`);
                      }}
                    >
                      {intl.formatMessage({ id: word })}
                    </div>
                  );
                })}
              </div>
            }
          >
            <Space
              align="center"
              size={1}
              className={!dark ? 'right_operate_word' : 'right_operate_dark_word'}
              style={{ cursor: 'pointer', fontWeight: 400 }}
            >
              {intl.formatMessage({ id: 'home.all_product' })}
              <img
                src={donwImg}
                style={{ ...(dark ? { filter: 'brightness(0.1)' } : {}) }}
                width={18}
              />
            </Space>
          </Popover>
        ) : null}
        {needWords ? (
          <>
            <Popover
              overlayClassName="code_popover"
              content={
                <div style={{ textAlign: 'center' }}>
                  <img src={code} width={160} />
                  <div style={{ fontSize: 10, color: '#424554' }}>
                    {intl.formatMessage({ id: 'home.scan' })}
                  </div>
                </div>
              }
              placement="topLeft"
            >
              <div
                className={!dark ? 'right_operate_word' : 'right_operate_dark_word'}
                onClick={donwLoad}
                style={{ cursor: 'pointer', fontWeight: 400 }}
              >
                {intl.formatMessage({ id: 'home.donwload' })}
              </div>
            </Popover>
            <div
              onClick={() => {
                jumpUrl('/join');
              }}
              className={!dark ? 'right_operate_word' : 'right_operate_dark_word'}
              style={{ cursor: 'pointer' }}
            >
              {intl.formatMessage({ id: 'home.operate' })}
            </div>
          </>
        ) : null}
        <Locale
          wordCss={{
            color,
            ...(dark ? { filter: 'brightness(0.1)' } : {}),
            fontSize: 16,
          }}
          localOverlayClassName={localOverlayClassName}
        />
        {!token ? (
          <Button
            onClick={() => {
              jumpUrl('/login');
            }}
            className="login_btn"
            style={{ color: '#0F294D' }}
          >
            {intl.formatMessage({ id: 'home.login' })}
          </Button>
        ) : (
          <Flex align="center" gap={10}>
            <div
              onClick={() => {
                jumpUrl('/center?index=2');
              }}
              style={{ position: 'relative', cursor: 'pointer' }}
            >
              <img src={require(`@/assets/${dark ? 'b_msg' : 'msg'}.png`)} width={21} height={21} />
              {hasMsg ? <div className="layout_circle" /> : null}
            </div>

            <Divider
              type="vertical"
              style={{
                borderColor: dark ? '#ccc' : 'rgba(255, 255, 255, 0.5)',
                height: 16,
                top: 1,
              }}
            />
            <Popover
              content={() => (
                <div style={{ padding: '6px 8px', width: 256 }}>
                  <div style={{ fontSize: 18, fontWeight: 'bold' }}>{newName}</div>
                  <div style={{ color: '#999' }}>ID：{userNo}</div>
                  {items.map((item, index) => {
                    const { label, key } = item;
                    return (
                      <div
                        className="topbar_item"
                        onClick={() => {
                          if (key == 5) {
                            localStorage.setItem('userInfo', '{}');
                            jumpUrl('/login');
                            setUser({});
                            message.success(intl.formatMessage({ id: 'app.login.out' }));
                          } else {
                            // 不存在跳去走流程
                            if (!finishFillInfoDate && pathname != '/info') {
                              jumpUrl('/info');
                              return;
                            }
                            jumpUrls(`index=${key - 1}`);
                          }
                        }}
                        key={key}
                      >
                        {index === items.length ? null : <Divider type="horizontal" />}
                        <Flex align="center" justify="space-between">
                          <div>{label}</div>
                          <div className="topbar_arrow" style={{ width: 18, height: 18 }} />
                        </Flex>
                      </div>
                    );
                  })}
                </div>
              )}
              placement="topRight"
            >
              <Space align="center" style={{ cursor: 'pointer', fontSize: 16 }}>
                <div>
                  <img
                    style={{ ...(dark ? { filter: 'brightness(0.1)' } : {}) }}
                    src={userImg}
                    width={21}
                    height={21}
                  />
                </div>
                {newName}
                <img
                  src={donwImg}
                  style={{ ...(dark ? { filter: 'brightness(0.1)' } : {}) }}
                  width={18}
                />
              </Space>
            </Popover>
          </Flex>
        )}
      </Space>
    </div>
  );

  return (
    <>
      {fixed && isFixed ? (
        <Affix offsetTop={!cookie ? 56 : 0} style={{ zIndex: 20, position: 'relative' }}>
          <div
            style={{
              backgroundColor: '#123BA4',
              height: '100%',
              width: '100vw',
              backgroundSize: '100% 100px',
              position: 'relative',
            }}
          >
            <div className="common" style={{ position: 'relative' }}>
              {/* <img src={g_bg} height={20} style={{ position: 'absolute', top: 0, right: 120 }} /> */}
              {compoennt({ padding: '14px 0', height: 62 })}
            </div>
          </div>
        </Affix>
      ) : (
        <div className={`${isCommon ? 'common' : ''}`}>{compoennt()}</div>
      )}
    </>
  );
};

export default TopBar;
